﻿using System.Reflection;
using Hangfire;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.OpenApi.Models;
using NanjingbeiRailwayStation.Core;
using NanjingbeiRailwayStation.WebApi.Filters;
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
using OTel.Exporter.Elasticsearch.Options;
using Elastic;
using Elastic.Apm;
using Elastic.Apm.Api;
using Elastic.Apm.NetCoreAll;

namespace NanjingbeiRailwayStation.WebApi
{
    /// <summary>
    /// 
    /// </summary>
    public class Program
    {

        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>

        public static void Main(string[] args)
        {

            //

            var builder = WebApplication.CreateBuilder(args);
 

             UsingOpenTelemetry(builder);
            //没有使用 builder.Services.AddAllElasticApm();
              
           var AllowSpecificOrigin = "AllowSpecificOrigin";

            builder
                .Services
            .AddCors(options =>
            {
                options.AddPolicy(AllowSpecificOrigin,
                    builder => builder
                    .AllowAnyOrigin() // 允许的源，可以添加多个源
                    .AllowAnyMethod() // 允许任何HTTP方法
                    .AllowAnyHeader()); // 允许任何头部
             
            });
       
            builder.Services.AddControllers();
            builder.Services.AddSignalR();


            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1",
                    new OpenApiInfo
                    {
                        Title = "南京北站 web API - V1",
                        Version = "v1"
                    }
                 );

                try
                {

                    c.IncludeXmlComments(Assembly.GetExecutingAssembly());
                    c.IncludeXmlComments(typeof(NanjingbeiRailwayStation.Core.Dir).Assembly);
                    c.IncludeXmlComments(typeof(NanjingbeiRailwayStation.Data.ClickHouse.Db).Assembly);
                    
                
                } catch (Exception ex)
                {

                }

                // or c.IncludeXmlComments(typeof(MyController).Assembly));
            });


            

            builder.WebHost.ConfigureKestrel(serverOptions =>
            {
                //serverOptions.ConfigureHttpsDefaults(listenOptions =>
                //{
                //    listenOptions.SslProtocols = SslProtocols.None;
                //});
                serverOptions.ListenAnyIP(8080);

            });

             
            var app = builder.Build();

            //app.UseSerilogRequestLogging(options =>
            //{
            //    // Customize the message template
            //    options.MessageTemplate = "Handled {RequestPath}";

            //    // Emit debug-level events instead of the defaults
            //    options.GetLevel = (httpContext, elapsed, ex) => LogEventLevel.Debug;

            //    // Attach additional properties to the request completion event
            //    options.EnrichDiagnosticContext = (diagnosticContext, httpContext) =>
            //    {
            //        diagnosticContext.Set("RequestHost", httpContext.Request.Host.Value);
            //        diagnosticContext.Set("RequestScheme", httpContext.Request.Scheme);
            //    };
            //});

            // Configure the HTTP request pipeline.

            app.UseSwagger();
            app.UseSwaggerUI();
            app.UseCors(AllowSpecificOrigin);
            app.MapControllers();

             

            app.MapHub<Hubs.MessageHub>("/messageHub", options =>
            {
                options.Transports =
                    HttpTransportType.WebSockets |

                    HttpTransportType.LongPolling;
            }
            ).RequireCors(t => t.SetIsOriginAllowed((host) => true)
                                .AllowAnyMethod()
                                .AllowAnyHeader()
                                .AllowCredentials());
  
            app.Run();
             
        }

 

        /// <summary>
        ///  请不要开启  nanjingbeirailwaystation_webapi
        /// </summary>
        /// <param name="builder"></param>
        public static void UsingOpenTelemetry(WebApplicationBuilder builder)
        {
            
            return;
            var serviceName = "nanjingbeirailwaystation_webapi";
             
            builder.Logging.AddOpenTelemetry(options =>
            {
                options.SetResourceBuilder(ResourceBuilder.CreateDefault()
                    .AddService(builder.Environment.ApplicationName));
                options.IncludeScopes = true;
#if DEBUG
                 options.AddConsoleExporter();
#endif

                options.AddElasticsearchExporter(new ElasticsearchExporterHttpOptions(serviceName, StringConstant.ElasticsearchUrl));
            
            });

            builder.Services
                .AddOpenTelemetry()
                .ConfigureResource(resourceBuilder => resourceBuilder
                    .AddService(serviceName, serviceInstanceId: Environment.MachineName))
                .WithTracing(traceBuilder => traceBuilder
                        .SetSampler(new AlwaysOnSampler())
                        .AddHttpClientInstrumentation()
                        .AddEntityFrameworkCoreInstrumentation()
                        .AddAspNetCoreInstrumentation(options =>
                        {
                            options.RecordException = true;
                            //只记录api
                            options.Filter = context =>
                            {
                                var path = context.Request.Path.Value;
                                if (path == null)
                                {
                                    return false;
                                }
                                if (path.ToLower().Contains("EventReport".ToLower()))
                                {
                                    return true;
                                }
                                if (path.ToLower().Contains("RealTimeElectricalParameters".ToLower()))
                                {
                                    return true;
                                }
                                if (path.ToLower().Contains("HealthMonitoring".ToLower()))
                                {
                                    return true;
                                }
                                return false;
                            };


                            // 增加client_ip到Activity.Tags
                            options.EnrichWithHttpRequest = (activity, request) =>
                            {
                                var clientIp = request.Headers["X-Forwarded-For"].FirstOrDefault() ?? request.HttpContext.Connection.RemoteIpAddress?.ToString();
                                if (!string.IsNullOrEmpty(clientIp)) activity.SetTag("client_ip", clientIp);
                            };
                        })
#if DEBUG
                     .AddConsoleExporter()

                     //.AddOtlpExporter(options =>
                     //{

                     //    options.Endpoint = new Uri(StringConstant.OtlpExporterTracesUrl);
                     //})

                     .AddZipkinExporter(options =>
                     {

                         options.Endpoint = new Uri(StringConstant.ZipkinUrl);
                     })

#endif
                    );
              
        }
    }
}
